#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/7/14 12:39
# @Author  : hyang
# @File    : single_log.py
# @Software: python_utils

import logging
from logging.handlers import RotatingFileHandler
import threading
from conf import settings


class SingletonLog(object):
    """
    记录日志的单例类
    """

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        mutex = threading.Lock()  # 创建锁
        mutex.acquire()  # 上锁，防止多线程下问题
        if not hasattr(cls, '_instance'):
            cls._instance = super(cls, SingletonLog).__new__(cls)
            # cls._instance = object.__new__(cls)
            cls._instance.log_file = settings.log_file
            cls._instance.logger = logging.getLogger(settings.logger_name)
            cls._instance.__config_logger()

        mutex.release()  # 解锁

        return cls._instance

    def get_logger(self):
        return self.logger  # 返回logger

    def __config_logger(self):
        # 设置日志格式
        formatter = logging.Formatter(settings.fmt, datefmt=settings.datefmt)

        if settings.console_log_on == 1:  # 如果开启控制台日志

            console = logging.StreamHandler()

            console.setLevel(settings.log_level_in_console)

            console.setFormatter(formatter)

            self.logger.addHandler(console)

            self.logger.setLevel(settings.log_level_in_console)

        if settings.logfile_log_on == 1:  # 如果开启文件日志

            rt_file_handler = RotatingFileHandler(self.log_file, maxBytes=settings.max_bytes_each,
                                                  backupCount=settings.backup_count, encoding='utf-8')
            rt_file_handler.setFormatter(formatter)

            self.logger.addHandler(rt_file_handler)

            self.logger.setLevel(settings.log_level_in_logfile)
